package com.fjnu.dao;
import java.util.Arrays;
import com.fjnu.dto.UserConditionDto;
import com.fjnu.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 根据用户名查询
    public User selectByUsername(String username) {
        String sql = "SELECT * FROM user WHERE username = ?";
        try {
            return jdbcTemplate.queryForObject(sql,
                    new BeanPropertyRowMapper<>(User.class), username);
        } catch (Exception e) {
            return null; // 用户名不存在返回null
        }
    }

    // 用户注册（插入用户）
    public int insert(User user) {
        String sql = "INSERT INTO user(username, password, score, create_time) " +
                "VALUES(?, ?, ?, NOW())";
        return jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getScore() == null ? 0 : user.getScore());
    }

    // 修改用户密码
    public int updatePassword(Integer userId, String newPassword) {
        String sql = "UPDATE user SET password = ? WHERE id = ?";
        return jdbcTemplate.update(sql, newPassword, userId);
    }

    // 条件查询总数
    public Long countByCondition(UserConditionDto condition) {
        StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM user WHERE 1=1");
        List<Object> params = new ArrayList<>();
        if (condition.getUsername() != null) {
            sql.append(" AND username LIKE ?");
            params.add("%" + condition.getUsername() + "%");
        }
        if (condition.getMinScore() != null) {
            sql.append(" AND score >= ?");
            params.add(condition.getMinScore());
        }
        if (condition.getMaxScore() != null) {
            sql.append(" AND score <= ?");
            params.add(condition.getMaxScore());
        }
        return jdbcTemplate.queryForObject(sql.toString(), Long.class, params.toArray());
    }

    // 条件分页查询
    public List<User> selectByCondition(UserConditionDto condition, int offset, int pageSize) {
        StringBuilder sql = new StringBuilder("SELECT * FROM user WHERE 1=1");
        List<Object> params = new ArrayList<>();
        if (condition.getUsername() != null) {
            sql.append(" AND username LIKE ?");
            params.add("%" + condition.getUsername() + "%");
        }
        if (condition.getMinScore() != null) {
            sql.append(" AND score >= ?");
            params.add(condition.getMinScore());
        }
        if (condition.getMaxScore() != null) {
            sql.append(" AND score <= ?");
            params.add(condition.getMaxScore());
        }
        sql.append(" LIMIT ?, ?");
        params.add(offset);
        params.add(pageSize);
        return jdbcTemplate.query(sql.toString(),
                new BeanPropertyRowMapper<>(User.class),
                params.toArray());
    }

    // 删除用户角色关联
    public int deleteUserRoles(Integer userId) {
        String sql = "DELETE FROM user_role WHERE user_id = ?";
        return jdbcTemplate.update(sql, userId);
    }

    // 批量插入用户角色关联
    public int batchInsertUserRoles(Integer userId, List<Integer> roleIds) {
        String sql = "INSERT INTO user_role(user_id, role_id) VALUES(?, ?)";
        int[] counts = jdbcTemplate.batchUpdate(sql, roleIds.stream()
                .map(roleId -> new Object[]{userId, roleId})
                .toList());
        return (int) Arrays.stream(counts).filter(c -> c > 0).count();
    }

    // 根据ID查询用户
    public User selectById(Integer id) {
        String sql = "SELECT * FROM user WHERE id = ?";
        try {
            return jdbcTemplate.queryForObject(sql,
                    new BeanPropertyRowMapper<>(User.class), id);
        } catch (Exception e) {
            return null;
        }
    }

    // 更新用户积分
    public int updateScore(Integer userId, Long newScore) {
        String sql = "UPDATE user SET score = ? WHERE id = ?";
        return jdbcTemplate.update(sql, newScore, userId);
    }
}